import { AndroidOutlined, RobotOutlined, UserOutlined } from "@ant-design/icons"
import { Avatar, Empty, FloatButton, List, Skeleton, Typography } from "antd"
import dayjs from "dayjs"
import React, {
  lazy,
  memo,
  Suspense,
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState
} from "react"

import MarkDownToHtml from "~components/MarkDownToHtml/MarkDownToHtml"
import { useChatStore } from "~store/chatStore"
import type { ChatMessageType } from "~type/chatType"
import { OIUUID } from "~util"

import ChatItem from "./ChatItem"
import ChatList from "./ChatList"

const ChatView = memo(({ isend }: { isend: boolean }) => {
  const messagesEndRef = useRef<HTMLDivElement>(null)
  const isBottom = useRef<boolean>(false)

  const scrollToBottom = () => {
    if (messagesEndRef.current && !isBottom.current) {
      console.log("scrollToBottom")
      isBottom.current = true
      const timer = setTimeout(() => {
        messagesEndRef.current.scrollIntoView({
          behavior: "smooth",
          block: "end",
          inline: "nearest"
        })
        isBottom.current = false
        clearTimeout(timer)
      }, 600)
    }
  }
  const endList = useMemo(() => isend, [isend])

  useEffect(() => {
    // console.log("dayjs", dayjs().valueOf())
    // scrollToBottom()
  }, [])
  useEffect(() => {
    // console.log("isend", isend)
    // endList && scrollToBottom()
  }, [endList])

  const chatList = useMemo(() => {
    return <ChatList isEnd={isend} onScrollToBottom={scrollToBottom}></ChatList>
  }, [endList])

  return (
    <>
      <div
        id="chatlist"
        className="w-full h-full overflow-y-auto overflow-x-hidden relative"
        onScroll={(e) => {
          // onChatListScorll(e)
        }}>
        {chatList}
        <NewChatItem isEnd={endList} onScrollBottom={scrollToBottom} />
        <div id="tobottom" ref={messagesEndRef}></div>
      </div>
    </>
  )
})

const NewChatItem = memo(
  ({
    isEnd,
    onScrollBottom
  }: {
    isEnd: boolean
    onScrollBottom: () => any | void
  }) => {
    const chat = useChatStore((state) => state.chat)
    const answer = useMemo(() => chat, [chat])
    const isend = useMemo(() => isEnd, [isEnd])
    useEffect(() => {
      onScrollBottom()
    }, [answer])
    if (chat && chat.content && chat.content.trim()) {
      return (
        <List.Item className={"min-w-0 w-full "}>
          <ChatItem
            item={answer}
            isend={isend}
            index={0}
            contents={[chat]}
            isdelayed={true}
          />
        </List.Item>
      )
    }
  }
)

export default ChatView
